package com.zk.transaction.service;

import com.zk.transaction.dao.AccountDao;
import com.zk.transaction.utils.JDBCUtils;
import com.zk.transaction.utils.JDBCUtils2;
import org.apache.commons.dbutils.DbUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class AccountService {
    /**
     * 使用DBUtils进行事务的管理:
     * @param from
     * @param to
     * @param money
     */
    public void transfer(String from, String to, Double money) {
        AccountDao accountDao = new AccountDao();
        Connection conn = JDBCUtils.getConnection();
        try {
            conn.setAutoCommit(false);
            accountDao.outMoney(conn,from ,money);
            int d = 1/ 0;
            accountDao.inMoney(conn,to,money);
            DbUtils.commitAndCloseQuietly(conn);
        } catch (Exception e) {
            DbUtils.rollbackAndCloseQuietly(conn);
            e.printStackTrace();
        }

    }

    /**
     * 事务管理的第二种方法:绑定到当前线程
     * @param from
     * @param to
     * @param money
     */
    public void transfer2(String from, String to, Double money) {
        AccountDao accountDao = new AccountDao();

        // 方式二:
        try {
            JDBCUtils2.beginTransaction();
            accountDao.outMoney2(from ,money);
            int d = 1/ 0;
            accountDao.inMoney2(to,money);
            JDBCUtils2.commitTransaction();
        } catch (Exception e) {
            try {
                JDBCUtils2.rollBackTransaction();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }

    }

    /**
     * 事务管理的第一种办法发:向下传递Connection:
     * 业务层转账的方法：
     * @param from
     * @param to
     * @param money
     */
    public void transfer1(String from, String to, Double money) {
        AccountDao accountDao = new AccountDao();

        // 方式一:在业务层获得Connection,传递给DAO。
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);
            //accountDao.outMoney(conn,from ,money);
            int d = 1/ 0;
            //accountDao.inMoney(conn,to,money);
            conn.commit();
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }

    }

}
